package com.xhwl.centiotdata.handler.pedestrian.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.handler.pedestrian.PedestrianIntegrationFactory;
import com.xhwl.centiotdata.handler.pedestrian.PedestrianIntegrationHandler;
import com.xhwl.centiotdata.pojo.dto.bailian.BaiLianDepartmentFlow;
import com.xhwl.centiotdata.pojo.dto.bailian.BaiLianStoreFlow;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.service.cent.IBiPedestrianCentService;
import com.xhwl.centiotdata.suppliersystem.bailian.PedestrianBaiLianHandler;
import com.xhwl.centiotdata.utils.ThreadPoolUtils;
import com.xhwl.common.dto.cent.iotdata.bailian.PedestrianSyncTaskDTO;
import com.xhwl.common.pojo.cent.bi.PedestrianRecordCompanyHour;
import com.xhwl.common.pojo.cent.bi.PedestrianRecordProjectHour;
import org.omg.CORBA.DATA_CONVERSION;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author： lianghz
 * @Description：
 * @Date 2021/09/20/ 10:06
 */
@Service
public class PedestrianIntegrationBaiLianHandler extends PedestrianIntegrationHandler {
    private static final Logger log = LoggerFactory.getLogger(PedestrianIntegrationBaiLianHandler.class);

    @Autowired
    private PedestrianBaiLianHandler pedestrianBaiLianHandler;
    @Autowired
    private IBiPedestrianCentService pedestrianCentService;

    @Override
    public void afterPropertiesSet() throws Exception {
        PedestrianIntegrationFactory.register(9, this);
    }


    private static final String[] WANDER_TIME_SYNC_CLOCKS = {"09:10", "10:00", "11:00"};

    /**
     * 该方法，每十分钟会调用一次，intervalDays =null, 每天也会调用一次，intervalDays = -1
     *
     * @param configDTO
     * @param intervalDays
     */
    @Override
    public void pullRecordStatistics(PedestrianIntegrationConfigDTO configDTO, Integer intervalDays) {

        /**
         * 每天固定时刻，拉取昨天的wanderTime数据
         */
        if (isWanderTimeUpdate()) {
            //更新昨日的wanderTime
            updateWanderTime(configDTO, -1);
        }

        if (intervalDays != null && intervalDays < 0) {
            //同步人行数据的时候，会覆盖wanderTime，所以如果是同步历史数据，需要再同步wanderTime
            ThreadPoolUtils.baiLianSyncExecutor.execute(() -> {
                try {
                    Thread.sleep(30 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("同步客流wanderTime.....");
                updateWanderTime(configDTO, intervalDays);
            });
        }

        JSONObject jsonObject = pedestrianBaiLianHandler.pullTodayRecord(configDTO, intervalDays);
        JSONArray departmentFlowArray = jsonObject.getJSONArray("departmentFlow");
        JSONArray storeFlowArray = jsonObject.getJSONArray("storeFlow");

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<BaiLianStoreFlow> storeFlowList = storeFlowArray.toJavaList(BaiLianStoreFlow.class);
        //同步大表
        if (!CollectionUtils.isEmpty(storeFlowList)) {
            List<PedestrianRecordProjectHour> recordProjectHours = storeFlowList.stream().map(storeFlow -> {
                PedestrianRecordProjectHour recordProjectHour = new PedestrianRecordProjectHour();
                recordProjectHour.setProjectId(configDTO.getProjectId());
                recordProjectHour.setInFlow(storeFlow.getPedestrianInFlow());
                recordProjectHour.setOutFlow(storeFlow.getPedestrianOutFlow());
                recordProjectHour.setTotalFlow(storeFlow.getPedestrianInFlow() + storeFlow.getPedestrianOutFlow());
                try {
                    recordProjectHour.setIngestionTime(formatter.parse(storeFlow.getTime()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return recordProjectHour;
            }).collect(Collectors.toList());
            pedestrianCentService.asyncRecordProjectHour(recordProjectHours);
        }
        //同步公司表
        List<BaiLianDepartmentFlow> departmentFlowList = departmentFlowArray.toJavaList(BaiLianDepartmentFlow.class);
        if (!CollectionUtils.isEmpty(departmentFlowList)) {
            List<PedestrianRecordCompanyHour> recordCompanyHours = departmentFlowList.stream().map(departmentFlow -> {
                PedestrianRecordCompanyHour recordCompanyHour = new PedestrianRecordCompanyHour();
                recordCompanyHour.setProjectId(configDTO.getProjectId());
                recordCompanyHour.setCompanyCode(departmentFlow.getDepartmentID());
                recordCompanyHour.setInFlow(departmentFlow.getPedestrianInFlow());
                recordCompanyHour.setOutFlow(departmentFlow.getPedestrianOutFlow());
                recordCompanyHour.setTotalFlow(departmentFlow.getPedestrianInFlow() + departmentFlow.getPedestrianOutFlow());
                try {
                    recordCompanyHour.setIngestionTime(formatter.parse(departmentFlow.getTime()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return recordCompanyHour;
            }).collect(Collectors.toList());
            pedestrianCentService.asyncRecordCompanyHour(recordCompanyHours);
        }
    }

    private boolean isWanderTimeUpdate() {
        SimpleDateFormat sbf = new SimpleDateFormat("HH:mm");
        String currentHour = sbf.format(new Date());
        for (int i = 0; i < WANDER_TIME_SYNC_CLOCKS.length; i++) {
            if (currentHour.equals(WANDER_TIME_SYNC_CLOCKS[i])) {
                return true;
            }
        }
        return false;
    }


    private void updateWanderTime(PedestrianIntegrationConfigDTO configDTO, Integer intervalDays) {
        JSONObject jsonObject = pedestrianBaiLianHandler.pullHistoryRecord(configDTO, intervalDays);
        JSONArray departmentFlowArray = jsonObject.getJSONArray("departmentFlow");
        JSONArray storeFlowArray = jsonObject.getJSONArray("storeFlow");

        //这个接口时间格式和today不一样
        //同步店铺的游逛时长
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        List<BaiLianDepartmentFlow> departmentFlowList = departmentFlowArray.toJavaList(BaiLianDepartmentFlow.class);
        if (!CollectionUtils.isEmpty(departmentFlowList)) {
            List<PedestrianRecordCompanyHour> recordCompanyHours = departmentFlowList.stream().map(departmentFlow -> {
                PedestrianRecordCompanyHour recordCompanyHour = new PedestrianRecordCompanyHour();
                recordCompanyHour.setProjectId(configDTO.getProjectId());
                recordCompanyHour.setCompanyCode(departmentFlow.getDepartmentID());
                recordCompanyHour.setWanderTime(departmentFlow.getWanderTime());
                try {
                    recordCompanyHour.setIngestionTime(formatter.parse(departmentFlow.getTime()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return recordCompanyHour;
            }).collect(Collectors.toList());
            pedestrianCentService.asyncRecordWanderTime(recordCompanyHours);
        }

        //同步大表的wanderTime
        List<BaiLianStoreFlow> storeFlowList = storeFlowArray.toJavaList(BaiLianStoreFlow.class);
        if (!CollectionUtils.isEmpty(storeFlowList)) {
            BaiLianStoreFlow storeFlow = storeFlowList.get(0);
            PedestrianRecordProjectHour pedestrianRecordProjectHour = new PedestrianRecordProjectHour();
            pedestrianRecordProjectHour.setWanderTime(storeFlow.getWanderTime());
            pedestrianRecordProjectHour.setProjectId(configDTO.getProjectId());
            try {
                pedestrianRecordProjectHour.setIngestionTime(formatter.parse(storeFlow.getTime()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            pedestrianCentService.asyncRecordProjectHourWander(pedestrianRecordProjectHour);
        }
    }


    @Override
    public String repairRecord(PedestrianIntegrationConfigDTO pedestrianIntegrationConfigDTO, String date) {
        PedestrianSyncTaskDTO syncRecord = pedestrianBaiLianHandler.getSyncRecord(pedestrianIntegrationConfigDTO, date);
        if (!syncRecord.isSuccess()) {
            return StringUtils.isEmpty(syncRecord.getErrorMsg()) ? "请求百联数据异常" : syncRecord.getErrorMsg();
        }
        boolean asyncSuccess = pedestrianCentService.asyncOneDayRecord(syncRecord.getPedestrianSyncDTO());
        return asyncSuccess ? null : "同步bi失败";
    }

}
